package com.sumer.psychology.photo.infrastructure.persistence.hibernate;

import com.sumer.psychology.common.persistence.hibernate.AbstractHibernateRepository;
import com.sumer.psychology.photo.domain.model.*;
import org.hibernate.Query;

import java.util.List;
import java.util.UUID;

/**
 * 照片资源库
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/1
 * Time: 10:17
 */
public class HibernatePhotoRepository extends AbstractHibernateRepository implements PhotoRepository {
    @Override
    public PhotoId nextIdentity() {
        return new PhotoId(UUID.randomUUID().toString());
    }

    @Override
    public void add(Photo aPhoto) {
        session().saveOrUpdate(aPhoto);
    }

    @Override
    public Photo ofPhotoId(PhotoId photoId) {
        Query query = session()
                .createQuery("from Photo where photoId=:phoneId and availability=:availability")
                .setParameter("phoneId", photoId)
                .setParameter("availability", PhotoAvailability.ACTIVE);

        return (Photo) query.uniqueResult();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Photo> ofAlbumId(AlbumId albumId) {
        Query query = session()
                .createQuery("from Photo where albumId=:albumId and availability=:availability")
                .setParameter("albumId", albumId)
                .setParameter("availability", PhotoAvailability.ACTIVE);

        return query.list();
    }
}
